package com.regex.web.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * 〈一句话功能简述〉<br> 
 * 图片上传Utils
 *
 * @author ocean
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Component
public class SaveUploadFile {
	
	@Value("${ckeditor.storage.image.path}")
	private String ckeditor_storage_image_path;
    
    /** 
     *  
     * @param formFile 上传的图片文件  上传到相对目录 服务器运行目录下
     * @param request 
     * @param saveName 保存的文件的名字 
     * @param ext 保存的文件的扩展名 
     * @return 
     * @throws FileNotFoundException 
     * @throws IOException 
     */  
    public String savePic(MultipartFile formFile, HttpServletRequest request,  
      String saveName, String ext) throws FileNotFoundException,  
      IOException {  
     
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH");  
     String savepath = "/image/brand/" + sdf.format(new Date());//构建图片保存的目录  
     //得到图片保存目录的真实路径  
     String realsavepath = request.getSession().getServletContext()  
       .getRealPath(savepath); 
     File logosavedir = new File(realsavepath);  
     //如果目录不存在就创建  
     if (!logosavedir.exists()) {
      logosavedir.mkdirs();  
     }  
     FileOutputStream fops = new FileOutputStream(new File(realsavepath,  
       saveName));  
     fops.write(formFile.getBytes());  
     fops.close();  
     
     return savepath + "/" + saveName;  
    }  
    
    /** 
     *  
     * @param formFile 上传的图片文件  上传文件到真实目录下 可在配置文件中指定绝对路径 picSaveRootPath 
     * @param request 
     * @param saveName 保存的文件的名字 
     * @param ext 保存的文件的扩展名 
     * @return 
     * @throws FileNotFoundException 
     * @throws IOException 
     */ 
    public  String saveTruePic(MultipartFile formFile, HttpServletRequest request,  
      String saveName, String ext) throws FileNotFoundException,  
      IOException {  
     
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH");  
     String savepath = "/images/brand/" + sdf.format(new Date());//构建图片保存的目录  
     //创建文件目录  
     File logosavedir = new File(ckeditor_storage_image_path + savepath);  
     //如果目录不存在就创建  
     if (!logosavedir.exists()) {
      logosavedir.mkdirs();  
     }  
     FileOutputStream fops = new FileOutputStream(new File(ckeditor_storage_image_path + savepath,  
       saveName));  
     fops.write(formFile.getBytes());  
     fops.close();  
     
     return savepath + "/" + saveName;  
    }  
    
    /**
     * 上传文件
     * @param formFile
     * @param request
     * @param saveName
     * @param ext
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public  String saveTrueFile(MultipartFile formFile, HttpServletRequest request,  
    	      String saveName, String ext) throws FileNotFoundException,  
    	      IOException {  
    	     
    	     SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH");  
    	     String savepath = "/images/brand/" + sdf.format(new Date());//构建图片保存的目录  
    	     //创建文件目录  
    	     File logosavedir = new File(ckeditor_storage_image_path + savepath);  
    	     //如果目录不存在就创建  
    	     if (!logosavedir.exists()) {
    	      logosavedir.mkdirs();  
    	     }  
    	     // 文件存在时重命名
    	     int i = 1;
    	     String fileNameArray[] = saveName.split("\\.");
    	     String saveNameTmp = saveName;
    	     while (true) {
    	    	 File file = new File(ckeditor_storage_image_path + savepath + "/" + saveNameTmp);
    	    	 if(file.exists()) {
    	    		 saveNameTmp = fileNameArray[0] + "("+i+")"+"." + ext; 
    	    	 } else {
    	    		 saveName = saveNameTmp;
    	    		 break;
    	    	 }
    	    	 i++;
    	    	 System.out.println(i);
    	     }
    	     FileOutputStream fops = new FileOutputStream(new File(ckeditor_storage_image_path + savepath,  
    	       saveName));  
    	     fops.write(formFile.getBytes());  
    	     fops.close();  
    	     
    	     return savepath + "/" + saveName;  
    	    }  
    
    /**
     * 
     * 功能描述: <br>
     * base64圖片上傳
     *
     * @param base64Img
     * @param request
     * @param saveName
     * @param ext
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public  String savePic(String base64Img, HttpServletRequest request,  
            String saveName, String ext) throws FileNotFoundException,  
            IOException {  
           
           SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH");  
           String savepath = "images/brand/" + sdf.format(new Date());//构建图片保存的目录  
           
           //得到图片保存目录的真实路径  
//           String realsavepath = request.getSession().getServletContext()  
//             .getRealPath(savepath);  
//           System.out.println(realsavepath);
//         realsavepath = realsavepath + "/" + saveName;
           //创建文件目录  
           if(GenerateImage(base64Img, savepath, saveName)) {
               return savepath + "/" + saveName;  
           } else {
               return "";
           }
           
          }  
    
    public String savePicBackRealPath(String base64Img, HttpServletRequest request,  
            String saveName, String ext) throws FileNotFoundException,  
            IOException {  
           
           SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH");  
           String savepath = "/image/brand/" + sdf.format(new Date());//构建图片保存的目录  
           //得到图片保存目录的真实路径  
           String realsavepath = request.getSession().getServletContext()  
             .getRealPath(savepath);  
           System.out.println(realsavepath);
//           realsavepath = realsavepath + "/" + saveName;
           //创建文件目录  
           if(GenerateImage(base64Img, realsavepath, saveName)) {
               return realsavepath + "/" + saveName;  
           } else {
               return "";
           }
           
          }  
    
  //base64字符串转化成图片  
    public  boolean GenerateImage(String imgStr, String imgFilePath, String saveName) {   //对字节数组字符串进行Base64解码并生成图片  
        if (imgStr == null) //图像数据为空  
            return false;  
        Decoder decoder = Base64.getDecoder();  
        try   
        {  
            //Base64解码  
            byte[] b = decoder.decode(imgStr);  
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }  
          //创建文件目录  
            File logosavedir = new File(ckeditor_storage_image_path + imgFilePath);  
//            File file = new File(ckeditor_storage_image_path + savepath + "/" + saveNameTmp);
            //如果目录不存在就创建  
            if (!logosavedir.exists()) {
             logosavedir.mkdirs();  
            }  
            OutputStream out = new FileOutputStream(new File(ckeditor_storage_image_path+imgFilePath, 
                    saveName));      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        }   
        catch (Exception e)   
        {  
            e.printStackTrace();
            return false;  
        }  
    }  
    
    
    private String strNetImageToBase64;
	public String NetImageToBase64(String netImagePath) {
	     ByteArrayOutputStream data = new ByteArrayOutputStream();
	    try {
	        // 创建URL
	        URL url = new URL(netImagePath);
	        byte[] by = new byte[1024];
	        // 创建链接
	        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	        conn.setRequestMethod("GET");
	        conn.setConnectTimeout(5000);

	        new Thread(new Runnable() {
	            @Override
	            public void run() {
	                try {
	                    InputStream is = conn.getInputStream();
	                    // 将内容读取内存中
	                    int len = -1;
	                    while ((len = is.read(by)) != -1) {
	                        data.write(by, 0, len);
	                    }
	                    // 对字节数组Base64编码
	                    
	                    Encoder encoder = Base64.getEncoder();
	                    String str = encoder.encodeToString(data.toByteArray());
	                    strNetImageToBase64 = str;
	                    System.out.println("网络图片转换Base64:" + strNetImageToBase64);
	                    // 关闭流
	                    is.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }).start();

	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return strNetImageToBase64;
	}


}
